package com.ynyr.jar.wss.config;

import com.corundumstudio.socketio.AuthorizationListener;
import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.HandshakeData;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;
import com.google.common.io.Files;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.util.ResourceUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@org.springframework.context.annotation.Configuration
public class WssConfig {

    private int port = 8080;

    private String host = "localhost";

    @Bean
    public SocketIOServer socketIOServer() throws IOException
    {
        Configuration config = new Configuration();
        config.setHostname(host);
        config.setPort(port);

        // 配置 ssl
        config.setKeyStorePassword("ynyr123456");
        InputStream stream = new FileInputStream(ResourceUtils.getFile("classpath:weixin.jks"));
        config.setKeyStore(stream);

        //该处可以用来进行身份验证
        config.setAuthorizationListener(new AuthorizationListener() {
            @Override
            public boolean isAuthorized(HandshakeData data) {
                //http://localhost:8081?username=test&password=test
                //例如果使用上面的链接进行connect，可以使用如下代码获取用户密码信息，本文不做身份验证
//              String username = data.getSingleUrlParam("username");
//              String password = data.getSingleUrlParam("password");
                return true;
            }
        });

        final SocketIOServer server = new SocketIOServer(config);

        return server;
    }

    /**
     * 自定义 Bean 扫描器.
     * @param socketServer
     * @return
     */
    @Bean
    public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketServer) {
        return new SpringAnnotationScanner(socketServer);
    }
}
